package nl.foldervisualizer.business
{
	import com.ericfeminella.collections.HashMap;
	import com.ericfeminella.collections.IMap;
	
	import flash.filesystem.File;
	
	public class FileUtils
	{		
		public static function addFilesRecurse(folder:File):IMap {
			var map:IMap = new HashMap()
			
			addFiles(folder, map)
			
			return aggregate(map, folder.nativePath)
		}
		
		/**
		 * Recursivelt adds all folders including the size of the files in the folders to the specified map and returns this map.
		 */
		private static function addFiles(folder:File, map:IMap):IMap {
			var files:Array = folder.getDirectoryListing()
			var count:int = 0
			for each (var file:File in files) {
				count++
				var key:String = file.parent.nativePath
				map.put(key, 0)
				if (!file.isDirectory) {
					key = key + File.separator + file.name
				} 
				map.put(key, file.size)
				if (file.isDirectory) {
					addFiles(file, map);
				}		
			}
			
			if (count == 0) {
				map.put(folder.nativePath, 0)
			}
				
			return map
		}
		
		private static function aggregate(map:IMap, parent:String):IMap {
			var aggregates:IMap = new HashMap()
			
			for each (var directory:String in map.getKeys()) {
				var value:Number = map.getValue(directory)
				computeSize(value, directory, aggregates)
				while (directory != parent) {
					directory = directory.substring(0, directory.lastIndexOf(File.separator))
					computeSize(value, directory, aggregates)
				}
			}
			
			return aggregates
		}
		
		private static function computeSize(value:Number, directory:String, aggregates:IMap):void {
			var size:Number = aggregates.getValue(directory)
			if (isNaN(size)) {
				size = 0
			}
			size += value
			aggregates.put(directory, size)
		}		
	}
}